<template>
	<view class="container">
		<view id="map" class="map" :prop="ydData" :change:prop="openGIS.getYd" :loc="location"
			:change:loc="openGIS.gotoLocation">

		</view>
		<view class="project-title" @click="showselectProject">
			{{queryProject.projectName}}
			<span v-if="!projectvisable">
				<uni-icons type="bottom" style="margin-top: 2rpx;" size="26"></uni-icons>
			</span>
			<span v-if="projectvisable">
				<uni-icons type="top" style="margin-top: 2rpx;" size="26"></uni-icons>
			</span>
		</view>
		<view class="project-box" v-show="projectvisable">
			<view class="project-item" v-for="(item,index) in projects" @click="selectProject(item)">
				{{item.projectName}}
			</view>

		</view>
		<!-- 	<view class="tools layer">

		</view> -->
		<view class="tools zoom">
			<view class="zoomGps" @click="openGIS.zoomLocation"></view>
			<view class="zoomIn" @click="openGIS.zoomIn"></view>
			<view class="zoomOut" @click="openGIS.zoomOut"></view>
		</view>
		<view class="tools measure">
			<view class="measureLength" @click="openGIS.measureLength"></view>
			<view class="measureArea" @click="openGIS.measureArea"></view>
			<view class="clearMeasure" @click="openGIS.measureClear"></view>

		</view>
		<uni-fab ref="fab" :pattern="pattern" :content="content" horizontal="left" vertical="bottom"
			direction="horizontal" @trigger="trigger" @fabClick="fabClick" />
		<uni-popup ref="popup" class="popup" :mask-click="false" background-color="#fff">
			<view class="popup-container">
				<view class="item">
					<view class="title">{{ydinfo.ydNumber}}</view>
					<uni-icons type="closeempty" class="icon" size="20" @click="toggleClose"></uni-icons>

				</view>
				<view class="address item">
					<view class="distance info">{{'距您'+(ydinfo.distance||'' )+"      " }}</view>
					<view class="location info">{{getxzqu(ydinfo)}}</view>
					<view class="gotonav info" @click="gotomap(ydinfo)">
						<image src="/static/mark.png"></image>
					</view>
				</view>
				<view class="item">
					<view class="surveyuser info">{{"调查人："+ userinfo.nickname}}</view>
					<view class="surveyuser info">{{"样地类型："+ (ydinfo.grasslandType=='人工草地'?'人工草地':'天然草地')}}</view>
				</view>
				<view class="item">
					<view class="lon info">{{"经度："+fixData(ydinfo.longitude)}}</view>
					<view class="coor info">{{" 纬度："+fixData(ydinfo.latitude)}}</view>
					<view class="coor info">{{" 海拔："+fixData(ydinfo.altitude)}}</view>
				</view>
				<view class="btns item">
					<button type="primary" class="btn" v-for="(item,index) in getBtns()" :key="index"
						@click="toCreate(item,ydinfo)">
						{{item}}
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getInfo
	} from '@/core/unicommon/storyageInfo.js'
	export default {
		data() {
			return {
				location: {},
				projectvisable: false,
				userdata: null,
				projects: [],
				ydinfo: {},
				ydData: [],
				userinfo: {},
				queryProject: {},
				content: [{
						iconPath: '/static/image.png',
						selectedIconPath: '/static/image-active.png',
						text: '卫星定位',
						active: false,
						nav: '/pages/compass/satellite'
					},
					{
						iconPath: '/static/home.png',
						selectedIconPath: '/static/home-active.png',
						text: '样地样方',
						active: false,
						nav: '/pages/sampleplot/sampleplot/poltlist'
					},
					{
						iconPath: '/static/star.png',
						selectedIconPath: '/static/star-active.png',
						text: '数据上报',
						active: false,
						nav: '/pages/user/user'
					}
				],
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				timer: null

			}
		},
		mounted() {

			this.timer = setInterval(this.getLocation(), 60000)
			this.ydData = []

			// let userdatares=uni.getStorageInfoSync("userdata")
			// this.userdata=userdatares.data
			// console.log(userdatares.data)
			// this.getProjects()
			getInfo("userdata").then(res => {
				this.userdata = res.data
				this.getProjects()
			})
			getInfo("userinfo").then(res => {
				this.userinfo = res.data
			})
		},
		onLoad() {
			this.ydData = []
			getInfo("userdata").then(res => {
				this.userdata = res.data
				this.getProjects()
			})
			getInfo("userinfo").then(res => {
				this.userinfo = res.data
			})


		},

		methods: {
			getLocation() {
				let that = this
				uni.getLocation({
					type: 'wgs84',
					success: (res => {
						that.location = {
							"latitude": res.latitude,
							"longitude": res.longitude,
						}
					})
				})
			},
			getxzqu(yd) {
				if (!yd) {
					return ""
				}
				let xzqh = ""
				if (yd.province) {
					let orgProvince = this.userdata.org.find(t => t.id == yd.province)
					xzqh += orgProvince.organizationName

					if (yd.city) {
						let orgCity = orgProvince.childOrganization.find(t => t.id == yd.city)
						xzqh += orgCity.organizationName

						if (yd.county) {
							let orgCounty = orgCity.childOrganization.find(t => t.id == yd.county)
							xzqh += orgCounty.organizationName

							if (yd.town) {
							
								xzqh += yd.town

								if (yd.village) {
								
									xzqh += yd.village
								}
							}
						}
					}
				}
				return xzqh

			},
			fixData(data) {
				if (data) {
					let num = parseFloat(data)
					return num.toFixed(3)
				} else {
					return ''
				}

			},
			toCreate(type, item) {
				console.log(type, item)
				if (type == '返青期') {
					uni.navigateTo({
						url: "/pages/sampleplot/sampleplot/greenPlot?data=" + encodeURIComponent(JSON.stringify(
							item))

					})

				} else if (type == '盛期') {

					uni.navigateTo({
						url: "/pages/sampleplot/sampleplot/peakPeriodPlot?data=" + encodeURIComponent(JSON
							.stringify(item))

					})


				} else {
					uni.navigateTo({
						url: "/pages/sampleplot/sampleplot/yellowPlot?data=" + encodeURIComponent(JSON.stringify(
							item))

					})
				}
				// if(item.grasslandType)

			},
			openPanel(data) {
				//处理行政区划
console.log("llll",data)
				this.ydinfo = data,
					this.toggleOpen()

			},
			/**
			 * 打开第三方导航
			 */
			gotomap(info) {
				console.log("bana", info)
				let that = this
				uni.showActionSheet({
					itemList: ['高德地图', '百度地图'],
					success: function(res) {
						that.guide(res.tapIndex, info)
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			guide(signMap, info) {
				uni.showLoading({
					title: '跳转中'
				});
				let lon = info.longitude
				let lati = info.latitude
				console.log(2222, info)
				if (!lon || !lati || lon == '' || lati == '') {
					return uni.showToast({
						title: '暂不知道该地点位置',
						icon: 'none',
						duration: 2000,
					});
				}
				let position = {
					name: '',
					longitude: lon,
					latitude: lati
				}

				console.log("123", position)
				let that = this

				if (position.longitude && position.longitude != '') {
					//地点位置position.name 地点经纬度lng lat
					var lng = position.longitude;
					var lat = position.latitude;
					// debugger;
					if (signMap == 0) {
						// 高德地图
						uni.getSystemInfo({
							success: (res) => {
								if (res.platform === "android") {
									let aurl = "androidamap://viewMap?sourceApplication=appname&poiname=" +
										position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									window.location.href = aurl
									try {
										let nurl = encodeURI(
											`amapuri://route/plan/?sid=&did=&dlat=${lat}&dlon=${lng}&dname=${position.name}&dev=0&t=0`
											)
											// #ifdef APP-PLUS
										plus.runtime.openURL(nurl, function(res) {
											console.log(res)
											uni.showModal({
												content: res.message
											})
										}, 'com.autonavi.minimap');
										plus.runtime.openURL(encodeURI(aurl), () => {}, 'com.autonavi.minimap')
										// #endif

									} catch (err) {
										console.log(err)
									}
									//判断是否跳转

									setTimeout(function() {
										let hidden = window.document.hidden || window.document
											.mozHidden || window.document.msHidden || window.document
											.webkitHidden
										if (typeof hidden == "undefined" || hidden == false) {
											let url = "https://uri.amap.com/marker?position=" + lng +
												"," +
												lat + "&name=" + position.name;
											//调用高德地图
											window.location.href = url
											// #ifdef APP-PLUS
											plus.runtime.openURL(url, function(res) {
												console.log(res)
												uni.showModal({
													content: res.message
												})
											}, 'com.autonavi.minimap');

											// #endif

										}
									}, 2000);
								} else {
									window.location.href =
										"iosamap://viewMap?sourceApplication=appname&poiname=" + position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									//判断是否跳转
									setTimeout(function() {
										let hidden = window.document.hidden || window.document
											.mozHidden || window.document.msHidden || window.document
											.webkitHidden
										if (typeof hidden == "undefined" || hidden == false) {
											//调用高德地图
											window.location.href =
												"https://uri.amap.com/marker?position=" + lng + "," +
												lat + "&name=" + position.name;
										}
									}, 2000);
								}
							}
						})
					} else if (signMap == 1) {
						// 百度地图
						uni.getSystemInfo({
							success: (res) => {
								if (res.platform === "android") {
									let d = new Date();
									let t0 = d.getTime();
									let url = "androidamap://viewMap?sourceApplication=appname&poiname=" +
										position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									window.location.href = url

									//由于打开需要1～2秒，利用这个时间差来处理－－打开app后，返回h5页面会出现页面变成app下载页面，影响用户体验
									var delay = setInterval(function() {
											// #ifdef APP-PLUS
										try {
											let nurl = encodeURI(
												`baidumap://map/direction?origin=${that.location.latitude},${that.location.longitude}&destination=name:${position.name}|latlng:${lat},${lng}&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo"`
											)
											plus.runtime.openURL(nurl, function(res) {
												console.log(res)
												uni.showModal({
													content: res.message
												})
											}, 'com.baidu.BaiduMap');
											plus.runtime.openURL(encodeURI(url), () => {},
												'com.baidu.BaiduMap')
										} catch (err) {
											console.log(err)

										}
										// #endif

									}, 1000);
								} else {
									let d = new Date();
									let t0 = d.getTime();
									window.location.href =
										"iosamap://viewMap?sourceApplication=appname&poiname=" + position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									//由于打开需要1～2秒，利用这个时间差来处理－－打开app后，返回h5页面会出现页面变成app下载页面，影响用户体验
									let delay = setInterval(function() {
										var d = new Date();
										var t1 = d.getTime();
										if (t1 - t0 < 3000 && t1 - t0 > 2000) {
											window.location.href =
												"http://api.map.baidu.com/marker?location=" + lat +
												"," + lng + "&title=" + position.name +
												"&content=地点&output=html&src=webapp.baidu.openAPIdemo";
										}
										if (t1 - t0 >= 3000) {
											clearInterval(delay);
										}
									}, 1000);
								}
							}
						})
					} else {
						// 腾讯地图
						uni.getSystemInfo({
							success: (res) => {
								if (res.platform === "android") {
									window.location.href =
										"androidamap://viewMap?sourceApplication=appname&poiname=" + position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									//判断是否跳转
									setTimeout(function() {
										let hidden = window.document.hidden || window.document
											.mozHidden || window.document.msHidden || window.document
											.webkitHidden
										if (typeof hidden == "undefined" || hidden == false) {
											//调用腾讯地图
											window.location.href =
												`https://apis.map.qq.com/uri/v1/marker?marker=coord:(${lat},${lng})&addr:${position.name}`
										}
									}, 2000);
								} else {
									window.location.href =
										"iosamap://viewMap?sourceApplication=appname&poiname=" + position
										.name + "&lat=" + lat + "&lon=" + lng + "&dev=0";
									//判断是否跳转
									setTimeout(function() {
										let hidden = window.document.hidden || window.document
											.mozHidden || window.document.msHidden || window.document
											.webkitHidden
										if (typeof hidden == "undefined" || hidden == false) {
											//调用高德地图
											window.location.href =
												`https://apis.map.qq.com/uri/v1/marker?marker=coord:(${lat},${lng})&addr:${position.name}`
										}
									}, 2000);
								}
							}
						})
					}
				} else {
					uni.showToast({
						title: '暂不知道该地点位置',
						icon: 'none',
						duration: 2000,
					});
				}
				setTimeout(function() {
					uni.hideLoading();
				}, 2000);
			},
			getBtns() {
				if (this.queryProject.surveyType) {
					return this.queryProject.surveyType.split(',')
				} else {
					return []
				}

			},
			getProjects(project) {

				this.projects = this.userdata.projects
				console.log(this.projects)
				if (!project) {
					this.queryProject = this.projects[0]
				}
				this.getYdData()

			},
			getYdData() {
				console.log(this.queryProject.projectName)
				this.ydData = this.userdata.yd.filter(t => t.projectName == this.queryProject.projectName)
				console.log("markd", this.queryProject.projectName, this.ydData.length)
			},

			selectProject(item) {

				this.queryProject = item
				this.projectvisable = false
				console.log("aaa", item, this.queryProject)
				this.getProjects(item)
			},
			showselectProject() {
				this.projectvisable = true
			},
			trigger(e) {
				if (e.item.text == "数据上报") {
					uni.switchTab({
						url: e.item.nav
					})
				} else {
					uni.navigateTo({
						url: e.item.nav
					});
				}
			},
			toggleOpen() {
				this.$refs.popup.open('bottom')
			},
			toggleClose() {
				this.$refs.popup.close()
			},
			fabClick(e) {
				console.log(111, e)
			}
		},
		onHide() {
			clearInterval(this.timer)
		}

	}
</script>
<script module="openGIS" lang="renderjs">
	import GIS from "@/core/ol/ol"
	import {
		diffDistance
	} from "@/core/ol/tools/gisMath"
	export default {
		data() {
			return {
				map: null,
				resource: require('@/common/resource.json'),

				iconimgs: "./static/location.png",
				locationmark: "./static/mark.png",


				yd: [],
				isRender: false,
				location: {}
			}
		},
		create() {

		},
		mounted() {
			// #ifdef H5
			this.iconimgs = "/static/location.png",
				this.locationmark = "/static/mark.png",
				// #endif
				console.log(this.iconimgs)
			this.initMap()
		},
		methods: {
			initMap() {
				let options = {
					container: 'map',
					baselayer: this.resource.basemap[9],
					center: [108.92, 34.23]
				}

				this.map = new GIS(options)
				// this.map.map.on('rendercomplete', () => {
				// this.map.addLayers(['yd'])
				// this.isRender = true
				// this.renderYd(this.yd)

				// })
				setTimeout(() => {
					this.map.addLayers(['yd'])
					this.isRender = true
					this.renderYd(this.yd)
					// this.map.registerEvent('loadend', this.onloadend)
					this.map.registerClickEvent('singleclick', this.onSingleClick)
				}, 500);



			},
			onloadend() {
				this.map.addLayers(['yd'])
				if (!this.isRender) {

					this.renderYd(this.yd)
				}
			},
			onSingleClick(graphic) {
				console.log("aaaa",graphic)
				let feature = graphic.getProperties()

				let start = [parseFloat(this.location.longitude), parseFloat(this.location.latitude)]
				//计算经距离
				let end = [parseFloat(feature.longitude), parseFloat(feature.latitude)]

				feature.distance = diffDistance(start, end)
				if(feature.ydNumber){
					this.$ownerInstance.callMethod("openPanel", feature)
				}


				

			},
			gotoLocation(location) {

				this.location = location
				if (this.map) {
					this.map.updateLoaction(location, this.locationmark)
				}
			},
			getYd(ydData) {

				let layer = this.map?.getLayer('yd')

				if (layer) {
					if (this.isRender) {

						this.renderYd(ydData)
					}

				} else {


					this.yd = ydData
				}


			},
			renderYd(yd) {
				let layer = this.map.getLayer('yd')
				this.map.clearPoints(layer)
				if (yd.length > 0) {
					yd.forEach(d => {

						if (d.longitude && d.latitude) {
							let coor = [parseFloat(d.longitude), parseFloat(d.latitude)]

							this.map.renderPoint(layer, coor, this.iconimgs, d.id, d)
						}
					})

					this.map.zoomToLayer(layer)
				}
			},
			zoomIn() {
				if (this.map) {
					this.map.zoomIn()
				}
			},
			zoomOut() {
				if (this.map) {
					this.map.zoomOut()
				}
			},
			zoomLocation() {
				if (this.map) {

					this.map.zoomToLocation()
				}

			},
			measureLength() {
				if (this.map) {
					this.map.measureLength()
				}

			},
			measureArea() {
				if (this.map) {
					this.map.measureArea()
				}
			},
			measureClear() {
				if (this.map) {
					this.map.measureClear()
				}
			}

		},
		onHide() {
			if (this.map) {
				this.map.destroy()
			}
		}

	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		width: 100%;

		.map {
			width: 100%;
			height: 100%;
		}

		.project-title {
			position: absolute;
			height: 120rpx;
			width: 100%;
			background-color: #3498db;
			z-index: 100;
			top: 0;
			text-align: center;
			line-height: 120rpx;
			font-size: 35rpx;
			cursor: pointer;
		}

		.project-box {
			position: absolute;
			width: 100%;
			top: 120rpx;

			.project-item {
				width: 80%;
				height: 60rpx;
				background-color: #fff;
				margin: 0 auto;
				text-align: center;
				border-bottom: 1px solid #ccc;
				line-height: 60rpx;
				text-overflow: ellipsis;
				overflow: hidden;
				word-break: break-all;
				white-space: nowrap;
			}

		}

		.tools {
			position: absolute;

			border-radius: 8rpx;
			// box-show:5rpx 5rpx;
			box-shadow: 2px 2px 10px #ccc;
			z-index: 10;

		}

		.layer {
			width: 65rpx;
			height: 65rpx;
			top: 180rpx;
			right: 20rpx;
			background-color: #fff;
			background-image: url("@/static/icons/layers.png");
			background-repeat: no-repeat;
			background-size: 50rpx 50rpx;
			background-position: center;

		}

		.zoom {
			width: 65rpx;
			height: 219rpx;
			right: 20rpx;
			bottom: 150rpx;

			.zoomGps {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				margin-bottom: 14rpx;
				border-radius: 8rpx;
				background-image: url("@/static/icons/location.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;
			}

			.zoomIn {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				border-bottom: 1px solid #bbb;

				border-top-left-radius: 8rpx;
				border-top-right-radius: 8rpx;
				background-image: url("@/static/icons/zoom_in.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;
			}

			.zoomOut {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				border-bottom-left-radius: 8rpx;
				border-bottom-right-radius: 8rpx;
				background-image: url("@/static/icons/zoom_out.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;

			}
		}

		.measure {
			width: 65rpx;
			height: 219rpx;
			left: 20rpx;
			bottom: 40%;

			.measureLength {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				border-bottom: 1px solid #bbb;
				border-top-left-radius: 8rpx;
				border-top-right-radius: 8rpx;
				background-image: url("@/static/icons/measure.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;
			}

			.measureArea {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				border-bottom-left-radius: 8rpx;
				border-bottom-right-radius: 8rpx;
				background-image: url("@/static/icons/area.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;
			}

			.clearMeasure {
				width: 65rpx;
				height: 65rpx;
				background-color: #fff;
				margin-top: 14rpx;
				border-radius: 8rpx;
				background-image: url("@/static/icons/eraser.png");
				background-repeat: no-repeat;
				background-size: 50rpx 50rpx;
				background-position: center;

			}

		}
	}

	.item {
		display: flex;
		height: 80rpx;
		margin-top: 10rpx;
		margin-bottom: 10rpx;

		.title {
			width: calc(100vw - 80rpx);
			text-align: center;
			font-size: 35rpx;
			font-weight: bold;

		}

		.icon {
			float: right;
			width: 80rpx;
		}

		.location {
			font-size: 24rpx;
		}

		.info {
			margin-left: 10rpx;
		}

		.coor {
			margin-left: 40rpx;
		}

		.distance {
			font-size: 24rpx;
		}

		.surveyuser {
			margin-right: 50rpx;
		}

		.btn {
			line-height: 80rpx;
		}

		.gotonav {
			width: 40rpx;
			height: 40rpx;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
</style>
<style>
	.ol-tooltip {
		position: relative;
		background: rgba(0, 0, 0, 0.5);
		border-radius: 4px;
		color: white;
		padding: 4px 8px;
		opacity: 0.7;
		white-space: nowrap;
		font-size: 12px;
		cursor: default;
		user-select: none;
	}

	.ol-tooltip-measure {
		opacity: 1;
		font-weight: bold;
	}

	.ol-tooltip-static {
		background-color: #ffcc33;
		color: black;
		border: 1px solid white;
	}

	.ol-tooltip-measure:before,
	.ol-tooltip-static:before {
		border-top: 6px solid rgba(0, 0, 0, 0.5);
		border-right: 6px solid transparent;
		border-left: 6px solid transparent;
		content: "";
		position: absolute;
		bottom: -6px;
		margin-left: -7px;
		left: 50%;
	}

	.ol-tooltip-static:before {
		border-top-color: #ffcc33;
	}

	.popup-container {
		padding-bottom: 120rpx
	}

	.item {
		display: flex;
		height: 80rpx;
		margin-top: 10rpx;
		margin-bottom: 10rpx;

		.title {
			width: calc(100vw - 80rpx);
			text-align: center;
			font-size: 35rpx;
			font-weight: bold;

		}

		.icon {
			float: right;
			width: 80rpx;
		}

		.location {
			font-size: 24rpx;
		}

		.info {
			margin-left: 10rpx;
		}

		.coor {
			margin-left: 40rpx;
		}

		.distance {
			font-size: 24rpx;
		}

		.surveyuser {
			margin-right: 50rpx;
		}

		.btn {
			line-height: 80rpx;
		}

		.gotonav {
			width: 40rpx;
			height: 40rpx;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
</style>